<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { fetchProjectsAPI } from '@/apis/fetchProjects'
import { useUserInfoStore } from '@/store/userInfo'

const router = useRouter()
const routerGuards = useRouterGuards()

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore } = useLoadMore<LoadMoreData<Project>>(
  fetchData,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

onReachBottom(() => loadMore())

/**
 * @description 分页服务函数
 */
async function fetchData(d?: LoadMoreData<Project>): Promise<LoadMoreData<Project>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchProjectsAPI(
    { page: _page.toString(), limit: '10' },
  )

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

function handleTapProjectCard(id: string) {
  routerGuards(() => {
    router.push({
      name: 'projectDetail',
      params: { id },
    })
  })
}
</script>

<template>
  <Spacer height="40" />
  <view v-if="dataList.length > 0">
    <ProjectItem
      v-for="item in dataList"
      :key="item.id"
      :picture="item.image"
      :title="item.title"
      :price="item.price"
      @tap="handleTapProjectCard(item.id.toString())"
    />
    <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
    <Spacer height="80" />
  </view>
  <PageDefault v-else>
    暂无服务项目
  </PageDefault>
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'projects'
style:
  navigationBarTitleText: '服务项目'
</route>
